<?php
namespace Admin\Controller;
use Think\Controller;
class IndexController extends Controller {
    public function index(){
        if ($_COOKIE['adminname'] == NULL) {
            $this->error('请登录','/bookManage/admin/index/login',1);
        }
    	$this->assign('userinfo',D('user')->limit('5')->order('addtime desc')->select());
    	$this->assign('usernum',D('user')->count());
    	$this->assign('booknum',D('book')->count());
        $this->display();
    }

    //登录
    public function login(){
    	if (IS_POST) {
			$userinfo = D('admin')->where("username='".I('post.username')."'")->find();
			if ($userinfo) {
				$username = $userinfo['username'];
				$password = $userinfo['password'];
				if($username == I('post.username') && $password == I('post.password')){
					cookie('adminname', $username);
					$this->success('登录成功','/bookManage/admin/index/index');exit;
				}else{
					$this->error('用户名或密码错误','/bookManage/admin/index/login',1);
				}
			}else{
				$this->error('用户名不存在','/bookManage/admin/index/login',1);
			}
    	}
    	$this->display();
    }

    //修改密码
    public function updatepwd(){
        if ($_COOKIE['adminname'] == NULL) {
            $this->error('请登录','/bookManage/admin/index/login',1);
        }
        if (IS_POST) {
        	$oldpwd = I('post.password');
        	$newpwd = I('post.newpassword');
        	$username = $_COOKIE['username'];
        	$userinfo = D('admin')->where("username='".$username."'")->find();
        	if ($userinfo['password'] == $oldpwd) {
        		if(D('admin')->where("username='".$username."'")->setField('password',$newpwd)){
        			cookie('username', NULL);
        			$this->success('修改成功, 请重新登录','/bookManage/admin/index/login');exit;
        		}else{
        			$this->error('修改失败','',1);exit;
        		}
        	}else{
        		$this->error('原密码输入错误','',1);exit;
        	}
        }
    	$this->display();
    }

    //退出
    public function logout(){
		cookie('adminname', NULL);
		$this->success('安全退出','/bookManage/admin/index/login');
    }
}